package com.wy.javaJarUtil;

import com.wy.commandUtil.ExecuteCommandUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class PackageJar {
    private static final String javac = "D:\\study_soft\\jdk\\java8u281\\bin\\javac.exe";
    private static final String jar = "D:\\study_soft\\jdk\\java8u281\\bin\\jar.exe";

    public static void main(String[] args) throws IOException, InterruptedException {
        compileAndPackage(
                "D:\\gitee_versionControllerProject\\easy-projects\\czb\\czb\\src\\main\\java",          // 源码目录
                "C:\\Users\\wy\\Desktop\\packageProject\\czb\\lib",                      // 依赖库目录
                "C:\\Users\\wy\\Desktop\\packageProject\\czb\\aa.jar",    // 输出jar路径
                "com.Application"                  // 主类名
        );
    }

    /**
     * 编译并打包源文件
     *
     * @param sourceDir 源文件目录
     * @param libDir    依赖库目录
     * @param outputJar 输出的jar文件路径
     * @param mainClass 主类的全限定名
     */
    public static void compileAndPackage(String sourceDir, String libDir, String outputJar, String mainClass) throws IOException, InterruptedException {
        // 1. 创建临时编译目录
        String tempClassDir = "temp_classes";
        new File(tempClassDir).mkdirs();

        // 2. 获取所有Java源文件
        List<String> javaFiles = new ArrayList<>();
        findJavaFiles(new File(sourceDir), javaFiles);

        if (javaFiles.isEmpty()) {
            throw new RuntimeException("未找到任何Java源文件在目录: " + sourceDir);
        }

        // 3. 编译
        List<String> command = new ArrayList<>();
        command.add(javac);
        command.add("-d");
        command.add(tempClassDir);
        command.add("-cp");
        command.add(libDir + "\\*");
        command.add("-encoding");
        command.add("UTF-8");
        command.addAll(javaFiles);
        ProcessBuilder compileBuilder = new ProcessBuilder(command);
        ExecuteCommandUtil.executeCommand(compileBuilder);

        // 3. 打包
        ProcessBuilder jarBuilder = new ProcessBuilder(
                jar,
                "cvfm",
                outputJar,
                createManifest(libDir),
                "-C", tempClassDir, "."
        );
        ExecuteCommandUtil.executeCommand(jarBuilder);

        // 4. 清理临时目录
        deleteDirectory(new File(tempClassDir));
    }

    /**
     * 创建MANIFEST.MF文件
     */
    private static String createManifest(String libDir) throws IOException {
        String manifestPath = "MANIFEST.MF";
        try (PrintWriter writer = new PrintWriter(manifestPath, "UTF-8")) {
            writer.println("Manifest-Version: 1.0");

            // 添加依赖库到Class-Path
            File lib = new File(libDir);
            if (lib.exists() && lib.isDirectory()) {
                StringBuilder cp = new StringBuilder("Class-Path: ");
                for (File jar : lib.listFiles((dir, name) -> name.endsWith(".jar"))) {
                    cp.append("lib/").append(jar.getName()).append(" ");
                }
                writer.println(cp.toString().trim());
            }
            writer.println();
        }
        return manifestPath;
    }

    /**
     * 递归删除目录
     */
    private static void deleteDirectory(File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteDirectory(file);
                }
            }
        }
        dir.delete();
    }

    /**
     * 递归查找Java源文件
     */
    private static void findJavaFiles(File dir, List<String> files) {
        if (dir.isDirectory()) {
            File[] children = dir.listFiles();
            if (children != null) {
                for (File child : children) {
                    if (child.isDirectory()) {
                        findJavaFiles(child, files);
                    } else if (child.getName().endsWith(".java")) {
                        files.add(child.getAbsolutePath());
                    }
                }
            }
        }
    }
}
